package com.estate.common.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * PostgreSQL JSONB 数据处理器 (Fastjson2版本) - 修复空值处理
 */
@MappedTypes({Object.class})
@MappedJdbcTypes({JdbcType.OTHER})
public class JsonbTypeHandler extends AbstractJsonTypeHandler<Object> {
    private final Class<?> type;

    public JsonbTypeHandler(Class<?> type) {
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        if (ps != null) {
            String jsonValue = toJson(parameter);

            // 如果是空字符串或null，设置为null
            if (StringUtils.isBlank(jsonValue)) {
                ps.setNull(i, java.sql.Types.OTHER);
            } else {
                PGobject jsonObject = new PGobject();
                jsonObject.setType("jsonb");
                jsonObject.setValue(jsonValue);
                ps.setObject(i, jsonObject);
            }
        }
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object value = rs.getObject(columnName);
        return parsePgObject(value);
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object value = rs.getObject(columnIndex);
        return parsePgObject(value);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object value = cs.getObject(columnIndex);
        return parsePgObject(value);
    }

    @Override
    protected Object parse(String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        // 如果是String类型，直接返回字符串
        if (type == String.class) {
            return json;
        }
        return JSON.parseObject(json, type);
    }

    @Override
    protected String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        // 如果已经是字符串，直接返回
        if (obj instanceof String) {
            String str = (String) obj;
            // 如果是空字符串或特殊格式，返回null
            if (StringUtils.isBlank(str) ||
                    "[null]".equals(str) ||
                    "\"\"".equals(str) ||
                    "null".equals(str)) {
                return null;
            }
            return str;
        }
        // 使用Fastjson2的JSON.toJSONString
        return JSON.toJSONString(obj, JSONWriter.Feature.WriteMapNullValue);
    }

    /**
     * 解析PGobject对象
     */
    private Object parsePgObject(Object value) {
        if (value instanceof PGobject) {
            PGobject pgObject = (PGobject) value;
            String pgValue = pgObject.getValue();
            if (StringUtils.isNotEmpty(pgValue) &&
                    ("jsonb".equals(pgObject.getType()) || "json".equals(pgObject.getType()))) {
                return parse(pgValue);
            }
        }
        return value;
    }
}